<template>
    <div class="medical-safety-container">
        <global-search @submitSearch="submitSearch" class="global-tool-search"/>
        <div class="page-height-box">
            <view-card :cardData="cardData"/>
            <div class="echart-table-box">
            <el-row :gutter="10">
                <el-col :span="12">
                    <div class="content">
                        <p class="title">入组分析</p>
                        <data-chart :chartData="joinEchart"/>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="content">
                        <div class="title-tool-btn">
                            <p class="title">覆盖组排名</p>
                            <el-radio-group v-model="coverName" @change="changeCover">
                                <el-radio-button label="覆盖MDC组数"></el-radio-button>
                                <el-radio-button label="覆盖ADRG组数"></el-radio-button>
                                <el-radio-button label="覆盖DRGs组数"></el-radio-button>
                            </el-radio-group>
                        </div>
                        <el-table
                            border
                            :data="coverTableData"
                            stripe
                            max-height="305"
                            tooltip-effect="light"
                            :empty-text="emptyTextDRG"
                            style="width: 100%">
                            <el-table-column
                                show-overflow-tooltip
                                prop="date"
                                align="center"
                                type="index"
                                label="排名"
                                min-width="60">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="key"
                                align="center"
                                label="编码"
                                min-width="120">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="value"
                                label="名称">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="count"
                                align="center"
                                label="病案数"
                                min-width="80">
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
                <el-col :span="24">
                    <div class="content">
                        <p class="title">产能分析</p>
                        <data-chart :chartData="capacityEchart"/>
                    </div>
                </el-col>
                <el-col :span="24">
                    <div class="content">
                        <div class="title-tool-btn">
                            <p class="title">汇总列表</p>
                            <el-button type="text" class="export-btn" v-auth="{code: 200004001001}" @click="toExport">
                                <svg-icon icon-class="export"/>
                                导出
                            </el-button>
                        </div>
                        <el-table
                            border
                            :data="tableData"
                            style="width: 100%"
                            tooltip-effect="light"
                            :empty-text="emptyText"
                            @selection-change="handleSelectionChange">
                            <el-table-column
                                show-overflow-tooltip
                                fixed
                                type="selection"
                                align="center"
                                width="30">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                fixed
                                prop="date"
                                align="center"
                                type="index"
                                label="序号"
                                width="40">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                fixed
                                prop="department"
                                align="left"
                                label="科室名称"
                                min-width="110">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="resident"
                                align="center"
                                v-if="isShowDoctor"
                                label="住院医生"
                                min-width="90">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                fixed
                                prop="totalCase"
                                align="center"
                                sortable
                                label="病案数"
                                min-width="70">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="adrgCoverage"
                                align="center"
                                sortable
                                label="覆盖ADRG组数"
                                min-width="120">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="drgCoverage"
                                align="center"
                                sortable
                                label="覆盖DRGs组数"
                                min-width="120">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="drgCase"
                                align="center"
                                sortable
                                label="入组病案数"
                                min-width="100">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="ungroup"
                                align="center"
                                sortable
                                label="未入组病案数"
                                min-width="105">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="excluded"
                                align="center"
                                sortable
                                label="排除组病案数"
                                min-width="110">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="weight"
                                align="center"
                                sortable
                                label="总权重"
                                min-width="70">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="cmiIndex"
                                align="center"
                                sortable
                                label="CMI"
                                min-width="80">
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="avgHosDay"
                                align="center"
                                sortable
                                min-width="90">
                                <template slot="header" slot-scope="scope">
                                    <el-tooltip class="item" effect="light" content="入组病案的平均住院日" placement="top">
                                        <span>平均住院日</span>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="totalFee"
                                align="center"
                                sortable
                                min-width="100">
                                <template slot="header" slot-scope="scope">
                                    <el-tooltip class="item" effect="light" content="入组病案的总住院费用之和" placement="top">
                                        <span>住院总费用</span>
                                    </el-tooltip>
                                </template>
                                <template slot-scope="scope">
                                    {{scope.row.totalFee | getMoneyNum}}
                                </template>
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="drgIncome"
                                align="right"
                                sortable
                                min-width="100">
                                <template slot="header" slot-scope="scope">
                                    <el-tooltip class="item" effect="light" content="统计入组病案数据 | DRG组标准费用-住院费用总费用" placement="top">
                                        <span>DRG盈亏</span>
                                    </el-tooltip>
                                </template>
                                <template slot-scope="scope">
                                    {{scope.row.drgIncome | getMoneyNum}}
                                </template>
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                label="操作"
                                align="center"
                                min-width="50"
                                fixed="right">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="toPageInfo(scope.row)">明细</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
            </el-row>
        </div>
        </div>
    </div>
</template>

<script>
    import {
        serviceOverview,
        serviceMDC,
        serviceADRG,
        serviceDRG,
        serviceCapacity,
        serviceSummary,
        exportServiceSummary
    } from '@/api/data-analysis/service-capabilities'
    import {getMoneyNum} from '@/utils/filters'
    import DataChart from '@/components/DataChart'
    import ViewCard from '@/components/ViewCard'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'Dashboard',
        data () {
            return {
                // 是否显示住院医生
                isShowDoctor: false,
                // 筛选条件（用于覆盖组排名使用）
                form: {},
                // 覆盖组排名选项
                coverName: '覆盖MDC组数',
                // 图表数据
                joinEchart: {
                    type: 'pie',
                    series: [],
                    id: 'joinEchart',
                    unit: '例'
                },
                capacityEchart: {
                    xAxis: [],
                    series: [{
                        name: 'DRGs入组数',
                        data: []
                    }, {
                        name: 'DRGs总权重',
                        data: []
                    }, {
                        name: 'CMI指数',
                        data: []
                    }],
                    rightData: ['DRGs入组数', 'DRGs总权重'],
                    id: 'capacityEchart'
                },
                // 卡片数据
                cardData: [
                    {
                        title: '总病案数',
                        data: 0,
                        tips: '符合当前筛选条件下的病案数',
                        pageName: 'ServiceListIndex',
                        tab: 'all'
                    }, {
                        title: '入组病案数',
                        data: 0,
                        scale: '0%',
                        tips: '已入组的病案数',
                        pageName: 'ServiceListIndex',
                        tab: 'included'
                    }, {
                        title: '未入组病案数',
                        data: 0,
                        scale: '0%',
                        tips: '无法入组的数据,(排除组不计算到未入组中)',
                        pageName: 'ServiceListIndex',
                        tab: 'not'
                    }, {
                        title: '排除组病案数',
                        data: 0,
                        scale: '0%',
                        tips: '根据《排除组规则》排除在外的病案数',
                        pageName: 'ServiceListIndex',
                        tab: 'exclude'
                    }, {
                        title: '总权重(RW)',
                        data: 0,
                        tips: '某DRG费用权重×该医院DRG病案数',
                        pageName: 'ServiceListIndex',
                        tab: 'all'
                    }, {
                        title: 'CMI指数',
                        data: 0,
                        tips: '（某DRG费用权重×该医院DRG病案数）/该医院全体病案数',
                        pageName: 'ServiceListIndex',
                        tab: 'all'
                    }
                ],
                // 表格数据
                tableData: [],
                // 覆盖组表格数据
                coverTableData: [],
                // 选中的数据
                multipleSelection: [],
                // 空数据时显示的文本内容
                emptyText: '暂无数据',
                emptyTextDRG: '暂无数据',
                // 使用储存的数据，不去请求
                useStoreOverview: false,
                useStoreCapacity: false,
                useStoreSummary: false,
                useStoreCover: false,
                // 导出的全部数据
                allexportData: []
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStoreOverview = this.$route.query.tags === 'tags'
            this.useStoreCapacity = this.$route.query.tags === 'tags'
            this.useStoreSummary = this.$route.query.tags === 'tags'
            this.useStoreCover = this.$route.query.tags === 'tags'
        },
        mounted () {
        },
        methods: {
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                this.form = form
                this.isShowDoctor = form.department !== ''
                this.getServiceOverview(form)
                this.getServiceCapacity(form)
                this.getServiceSummary(form)
                this.changeCover()
            },
            /**
             * 切换覆盖组排名
             */
            changeCover () {
                this.coverTableData = []
                switch (this.coverName) {
                case '覆盖MDC组数':
                    this.getServiceMDC(this.form)
                    break
                case '覆盖ADRG组数':
                    this.getServiceADRG(this.form)
                    break
                case '覆盖DRGs组数':
                    this.getServiceDRG(this.form)
                    break
                }
            },
            /**
             * 服务能力总览查询
             * @param params 查询参数
             */
            getServiceOverview (params) {
                if (this.getSession(this.$route.name, 'serviceOverview') && this.useStoreOverview) {
                    this.useStoreOverview = false
                    let res = this.getSession(this.$route.name, 'serviceOverview')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.cardData[0].data = res.data.totalCase
                        this.cardData[1].data = res.data.group
                        this.cardData[1].scale = res.data.grouprate
                        this.cardData[2].data = res.data.ungroup
                        this.cardData[2].scale = res.data.ungroupRate
                        this.cardData[3].data = res.data.excluded
                        this.cardData[3].scale = res.data.excludedRate
                        this.cardData[4].data = res.data.weight
                        this.cardData[5].data = res.data.cmiIndex
                        this.joinEchart = {
                            type: 'pie',
                            series: [
                                {value: res.data.group, name: '入组占比'},
                                {value: res.data.ungroup, name: '未入组占比'},
                                {value: res.data.excluded, name: '排除组占比'}
                            ],
                            id: 'joinEchart',
                            unit: '例'
                        }
                    }
                } else {
                    serviceOverview(params).then(res => {
                        this.useStoreOverview = false
                        this.setSession(this.$route.name, {serviceOverview: res})
                        if (res.code.toString() === '200') {
                            this.cardData[0].data = res.data.totalCase
                            this.cardData[1].data = res.data.group
                            this.cardData[1].scale = res.data.grouprate
                            this.cardData[2].data = res.data.ungroup
                            this.cardData[2].scale = res.data.ungroupRate
                            this.cardData[3].data = res.data.excluded
                            this.cardData[3].scale = res.data.excludedRate
                            this.cardData[4].data = res.data.weight
                            this.cardData[5].data = res.data.cmiIndex
                            this.joinEchart = {
                                type: 'pie',
                                series: [
                                    {value: res.data.group, name: '入组占比'},
                                    {value: res.data.ungroup, name: '未入组占比'},
                                    {value: res.data.excluded, name: '排除组占比'}
                                ],
                                id: 'joinEchart',
                                unit: '例'
                            }
                        }
                    })
                }
            },
            /**
             * MDC查询
             * @param params 查询参数
             */
            getServiceMDC (params) {
                this.emptyTextDRG = '加载中...'
                if (this.getSession(this.$route.name, 'serviceMDC') && this.useStoreCover) {
                    this.useStoreCover = false
                    let res = this.getSession(this.$route.name, 'serviceMDC')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.coverTableData = res.data
                    }
                } else {
                    serviceMDC(params).then(res => {
                        this.useStoreCover = false
                        this.setSession(this.$route.name, {serviceMDC: res})
                        this.emptyTextDRG = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.coverTableData = res.data
                        }
                    }).catch(() => {
                        this.emptyTextDRG = '暂无数据'
                    })
                }
            },
            /**
             * ADRG查询
             * @param params 查询参数
             */
            getServiceADRG (params) {
                this.emptyTextDRG = '加载中...'
                if (this.getSession(this.$route.name, 'serviceADRG') && this.useStoreCover) {
                    this.useStoreCover = false
                    let res = this.getSession(this.$route.name, 'serviceADRG')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.coverTableData = res.data
                    }
                } else {
                    serviceADRG(params).then(res => {
                        this.useStoreCover = false
                        this.setSession(this.$route.name, {serviceADRG: res})
                        this.emptyTextDRG = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.coverTableData = res.data
                        }
                    }).catch(() => {
                        this.emptyTextDRG = '暂无数据'
                    })
                }
            },
            /**
             * DRG查询
             * @param params 查询参数
             */
            getServiceDRG (params) {
                this.emptyTextDRG = '加载中...'
                if (this.getSession(this.$route.name, 'serviceDRG') && this.useStoreCover) {
                    this.useStoreCover = false
                    let res = this.getSession(this.$route.name, 'serviceDRG')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.coverTableData = res.data
                    }
                } else {
                    serviceDRG(params).then(res => {
                        this.useStoreCover = false
                        this.setSession(this.$route.name, {serviceDRG: res})
                        this.emptyTextDRG = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.coverTableData = res.data
                        }
                    }).catch(() => {
                        this.emptyTextDRG = '暂无数据'
                    })
                }
            },
            /**
             * 产能分析查询
             * @param params 查询参数
             */
            getServiceCapacity (params) {
                if (this.getSession(this.$route.name, 'serviceCapacity') && this.useStoreCapacity) {
                    this.useStoreCapacity = false
                    let res = this.getSession(this.$route.name, 'serviceCapacity')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.capacityEchart = {
                            xAxis: res.data.month,
                            series: [{
                                name: 'DRGs入组数',
                                data: res.data.num
                            }, {
                                name: 'DRGs总权重',
                                data: res.data.weight
                            }, {
                                name: 'CMI指数',
                                data: res.data.cmiIndex
                            }],
                            rightData: ['DRGs入组数', 'DRGs总权重'],
                            id: 'capacityEchart'
                        }
                    }
                } else {
                    serviceCapacity(params).then(res => {
                        this.useStoreCapacity = false
                        this.setSession(this.$route.name, {serviceCapacity: res})
                        if (res.code.toString() === '200') {
                            this.capacityEchart = {
                                xAxis: res.data.month,
                                series: [{
                                    name: 'DRGs入组数',
                                    data: res.data.num
                                }, {
                                    name: 'DRGs总权重',
                                    data: res.data.weight
                                }, {
                                    name: 'CMI指数',
                                    data: res.data.cmiIndex
                                }],
                                rightData: ['DRGs入组数', 'DRGs总权重'],
                                id: 'capacityEchart'
                            }
                        }
                    })
                }
            },
            /**
             * 汇总列表查询
             * @param params 查询参数
             */
            getServiceSummary (params) {
                this.emptyText = '加载中...'
                if (this.getSession(this.$route.name, 'serviceSummary') && this.useStoreSummary) {
                    this.useStoreSummary = false
                    let res = this.getSession(this.$route.name, 'serviceSummary')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.tableData = res.data
                        this.tableData.forEach((item, index) => {
                            this.tableData[index] = {
                                ...item,
                                index
                            }
                        })
                    }
                } else {
                    serviceSummary(params).then(res => {
                        this.useStoreSummary = false
                        this.setSession(this.$route.name, {serviceSummary: res})
                        this.emptyText = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.tableData = res.data
                            this.tableData.forEach((item, index) => {
                                this.tableData[index] = {
                                    ...item,
                                    index
                                }
                            })
                        }
                    }).catch(() => {
                        this.emptyText = '暂无数据'
                    })
                }
            },
            /**
             * 表格数据选中
             */
            handleSelectionChange (val) {
                this.multipleSelection = val
            },
            /**
             * 获取选中id
             */
            getSelectId () {
                let arr = []
                if (this.multipleSelection.length) {
                    this.multipleSelection.forEach(item => {
                        arr.push(item.index)
                    })
                    return arr
                } else {
                    return false
                }
            },
            /**
             * 导出汇总列表
             */
            toExport () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                params.indexList = this.getSelectId() || []
                this.$store.dispatch('app/UpdateLoadingText', '0%')
                this.$store.dispatch('app/UpdateIsExport', true)
                this.$store.dispatch('app/UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                exportServiceSummary(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('app/UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('服务能力汇总列表', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('app/UpdateIsExport', false)
                        this.$store.dispatch('app/UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                let arr = [{
                    header: '序号', key: 'index', width: 10
                }, {
                    header: '科室名称', key: 'department', width: 16
                }, {
                    header: '住院医生', key: 'resident', width: 12
                }, {
                    header: '病案数', key: 'totalCase', width: 12
                }, {
                    header: '覆盖ADRG组数', key: 'adrgCoverage', width: 12
                }, {
                    header: '覆盖DRGs组数', key: 'drgCoverage', width: 12
                }, {
                    header: '入组病案数', key: 'drgCase', width: 12
                }, {
                    header: '未入组病案数', key: 'ungroup', width: 12
                }, {
                    header: '排除组病案数', key: 'excluded', width: 12
                }, {
                    header: '总权重', key: 'weight', width: 12
                }, {
                    header: 'CMI', key: 'cmiIndex', width: 16
                }, {
                    header: '平均住院日', key: 'avgHosDay', width: 16
                }, {
                    header: '住院总费用', key: 'totalFee', width: 32
                }, {
                    header: 'DRG盈亏', key: 'drgIncome', width: 32
                }]
                if (!this.isShowDoctor) {
                    arr.splice(2, 1)
                }
                return arr
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                worksheet.columns = this.getHeader()
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    data[i].totalFee = getMoneyNum(data[i].totalFee)
                    data[i].drgIncome = getMoneyNum(data[i].drgIncome)
                    worksheet.addRow(data[i])
                    worksheet.getRow(i + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('app/UpdateLoadingText', rate)
                }
                worksheet.getRow(data.length + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('department').alignment = {wrapText: true, vertical: 'middle', horizontal: 'left'}
                worksheet.getColumn('drgIncome').alignment = {wrapText: true, vertical: 'middle', horizontal: 'left'}
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('app/UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('app/UpdateLoadingText', '100%')
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                })
            },
            /**
             * 查看数据详情
             * @param row 行数据
             */
            toPageInfo (row) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                this.setGetStore('ServiceListIndex', {...query, department: row.dep, depName: row.department, resident: this.isShowDoctor ? row.resident : ''})
                this.$router.push({name: 'ServiceListIndex', query: {department: row.dep, depName: row.department}})
            }
        },
        filters: {
            getMoneyNum
        },
        components: {
            ViewCard,
            DataChart
        }
    }
</script>

<style scoped lang="scss">
    .medical-safety-container {
        .echart-table-box {
            .el-col {
                &:nth-child(4) {
                    margin-bottom: 0;
                    height: auto;
                }
            }
        }
    }
</style>
